package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Zheng
 * Date:   2024/2/19  20:27
 * Package：com.sky.service.impl
 * Description：菜品业务逻辑处理层
 * Version：1.0
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * @param dishDTO
     * @description： 新增菜品和对应口味数据
     * @date：2024/2/19 20:34
     * @return：
     */
    @Override
    @Transactional
    public void insert(DishDTO dishDTO) {

        //创建菜品对象
        Dish dish = new Dish();
        //将dishDTO属性拷贝到dish对象
        BeanUtils.copyProperties(dishDTO, dish);

        //向菜品表中插入一条数据
        dishMapper.insert(dish);

        //获取insert生成的主键id
        Long id = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(id));
        }
        dishFlavorMapper.insertBatch(flavors);

    }

    /**
     * @param dto
     * @description：菜品分页查询
     * @date：2024/2/19 22:38
     * @return：
     */
    @Override
    public PageResult page(DishPageQueryDTO dto) {
        PageMethod.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> page = dishMapper.page(dto);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * @param ids
     * @description： 菜品批量删除
     * @date：2024/2/19 23:17
     * @return：
     */
    @Override
    @Transactional //开启事务
    public void deleteBatch(Long[] ids) {

        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            //如果菜品状态为起售，则禁止删除
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }

            Integer count = setmealDishMapper.count(id);

            if (count > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        dishMapper.deleteBatch(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * @param id
     * @description： 根据id查询菜品, 回显数据
     * @date：2024/2/20 8:58
     * @return：
     */
    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = new DishVO();
        //根据菜品id查询菜品的基本信息，封装到DishVO对象中
        Dish dish = dishMapper.getById(id);
        BeanUtils.copyProperties(dish, dishVO);

        //根据菜品id查询口味信息，将其封装到DishVO对象
        List<DishFlavor> flavors = dishFlavorMapper.getByDishIds(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * @param dishDTO
     * @description： 修改菜品
     * @date：2024/2/20 9:17
     * @return：
     */
    @Override
    @Transactional //开启事务
    public void update(DishDTO dishDTO) {
        //1.修改菜品基本信息（dish表）
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        //2.修改口味列表信息（dish_flavor表）
        //有三种情况：新增一个新口味、删除一个旧口味、修改就口味
        //直接删除原来的口味数据，再将页面传递过来的所有口味数据插入到表中
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();

        //关联菜品id(因为新的口味数据是没有关联菜品的)
        if (!flavors.isEmpty()){

        flavors.forEach(flavor -> flavor.setDishId(dishDTO.getId()));
        dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * @param status
     * @param id
     * @description： 菜品起售停售
     * @date：2024/2/20 10:21
     * @return：
     */
    @Override
    @Transactional //开启事务
    public void startOrStop(Integer status, Long id) {

        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);

        if (status.equals(StatusConstant.DISABLE)) {
            //如果是停售，需要同时将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (!setmealIds.isEmpty()){
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * @param categoryId
     * @description： 根据分类id查询菜品数据
     * @date：2024/2/20 12:09
     * @return：
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId,String name) {
        List<Dish> dishList = dishMapper.getByCategoryId(categoryId,name);
        return dishList;
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishIds(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
